package com.xinqi.modules.third.service.impl;

import com.xinqi.common.base.response.R;
import com.xinqi.common.third.checkarea.CheckArea;
import com.xinqi.modules.third.service.CheckAreaService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Log4j2
@Service
public class CheckAreaServiceImpl implements CheckAreaService {


    @Override
    public R<String> checkArea(String mobile, HttpServletRequest request) {
        String ip = getPublicIPAddress(request);
        boolean ipFlag = CheckArea.checkIpArea(ip);
        boolean mobileFlag = CheckArea.checkPhoneArea(mobile);
        if (ipFlag && mobileFlag) {
            return R.ok("认证成功");
        } else {
            return R.fail("账号未认证，请联系学校开通认证！");
        }
    }

    /**
     * 获取公网IP地址
     */
    public String getPublicIPAddress(HttpServletRequest request) {
        String ipAddress = request.getRemoteHost();
        // DNS解析下获取
        if (Objects.isNull(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        // 代理服务器下获取
        if (Objects.isNull(ipAddress)) {
            ipAddress = request.getHeader("X-Forwarded-For");
        }
        log.error("获取IP地址:" + ipAddress);
        return ipAddress;
    }
}
